package com.xiyue.leaspring.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.xiyue.leaspring.dao.INewsDao;
import com.xiyue.leaspring.service.INewsService;
import com.xiyue.leaspring.utils.DefaultRedisCache;
import com.xiyue.leaspring.vo.News;

@Service
public class MewsServiceImpl implements INewsService {

	@Autowired
	private INewsDao newsDao;
	
	@Autowired
	private PlatformTransactionManager transactionManager;
	
	DefaultRedisCache DefaultRedisCache = new DefaultRedisCache();
	
	
	@Override
	public News get(Long nid) {
		News vo = null;
		//TransactionDefinition通过此类设置传播属性、隔离级别、是否为只读、超时访问
		DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
		//设置传播性，必须有一个事务存在
		defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		//使用默认隔离级别进行控制
		defaultTransactionDefinition.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
		defaultTransactionDefinition.setReadOnly(true);//只读操作
		TransactionStatus transactionStatus =
				this.transactionManager.getTransaction(defaultTransactionDefinition);//获取事务状态
		try {
			vo = this.newsDao.findById(nid);
			this.transactionManager.commit(transactionStatus);//提交事务
		} catch (Exception e) {
			this.transactionManager.rollback(transactionStatus);//回滚到指定提交点
		}
		return vo;
	}


	@Override
	public News edit(News vo) {
		if(this.newsDao.doUpdate(vo)) {
			return vo;
		}
		return null;
	}


	@Override
	public boolean delete(long nid) {
		boolean flag = false;
		//TransactionDefinition通过此类设置传播属性、隔离级别、是否为只读、超时访问
		DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
		//设置传播性，必须有一个事务存在
		defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		//使用默认隔离级别进行控制
		defaultTransactionDefinition.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
		TransactionStatus transactionStatus =
				this.transactionManager.getTransaction(defaultTransactionDefinition);//获取事务状态
		try {
			flag = this.newsDao.doRemove(nid);
			this.transactionManager.commit(transactionStatus);//提交事务
		} catch (Exception e) {
			this.transactionManager.rollback(transactionStatus);//回滚到指定提交点
		}
		return flag;
		
	}


	@Override
	public int save(News vo) {
		return this.newsDao.doSave(vo);
	}


	@Override
	public void batchSave(List<News> allnews) {
		this.newsDao.batchSave(allnews);
	}

}
